package com.tanhua.manager.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.UserFreeze;
import com.itheima.domain.db.UserUnfreezeLog;
import com.itheima.domain.vo.ErrorResult;
import com.itheima.domain.vo.UserFreezeVo;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.mapper.UserFreezeMapper;
import com.tanhua.manager.mapper.UserUnfreezeLogMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * @author Mr.Seven的基操
 * @date 2021/03/01 22:45
 */
@Service
public class UserFreezeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String MESSAGE = "操作成功";


    @Autowired
    private UserFreezeMapper userFreezeMapper;
    @Autowired
    private UserUnfreezeLogMapper unfreezeLogMapper;

    /**
    Mr.Seven的基操
     */
    public ResponseEntity freezeUser(UserFreezeVo userFreezeVo) {
        try {
            // 判断前台接收的数据是否正确,不正确直接返回401
            if (userFreezeVo == null) {
                return ResponseEntity.badRequest().build();
            }

            UserFreeze userFreeze = this.userFreezeMapper.findByUserId(userFreezeVo.getUserId());
            // 如果数据库能查询出来,说明用户已经被封禁了
            if (userFreeze != null) {
                // 此时如果发请求到这,说明数据还是不正常,可能是前端的问题
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }

            userFreeze = new UserFreeze();
            BeanUtils.copyProperties(userFreezeVo, userFreeze);
            userFreeze.setFreezeDate(DateUtil.date(new Date()));
            userFreeze.setCreated(new Date());
            userFreeze.setUpdated(new Date());

            // 将UserFreeze 保存到数据库
            this.userFreezeMapper.insert(userFreeze);

            if (userFreezeVo.getFreezingTime() == 1) {
                redisTemplate.opsForValue().set(CacheKey.FREEZE_PREFIX + userFreezeVo.getUserId(), "1", Duration.ofDays(3));
            } else if (userFreezeVo.getFreezingTime() == 2) {
                redisTemplate.opsForValue().set(CacheKey.FREEZE_PREFIX + userFreezeVo.getUserId(), "2", Duration.ofDays(7));
            } else if (userFreezeVo.getFreezingTime() == 3) {
                redisTemplate.opsForValue().set(CacheKey.FREEZE_PREFIX + userFreezeVo.getUserId(), "3");
            } else {
                // 此时是怕前台传过来的数据有误
                return ResponseEntity.badRequest().body("数据有误");
            }

            return ResponseEntity.ok(MESSAGE);
        } catch (BeansException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResult.error());
        }
    }

    /**
    Mr.Seven的基操
     */
    @Transactional
    public ResponseEntity unfreezeUser(Long userId, String reasonsForThawing, String frozenRemarks) {
        try {
            // 校验前台数据
            if (userId == null || reasonsForThawing == null) {
                return ResponseEntity.badRequest().build();
            }

            // 从数据库查询当前id
            UserFreeze freeze = this.userFreezeMapper.findByUserId(userId);
            if (freeze == null) {
                // 说明当前用户没有被封禁,前台传输数据有问题
                return ResponseEntity.badRequest().build();
            }

            // 将本次操作的行为记录到tb_user_unfreeze_log表中
            UserUnfreezeLog unfreezeLog = new UserUnfreezeLog();
            // 解封原因
            if (StringUtils.isNotBlank(reasonsForThawing)) {
                unfreezeLog.setReasonsForThawing(reasonsForThawing);
            } else {
                unfreezeLog.setReasonsForThawing("人工解封");
            }
            // 解封备注
            unfreezeLog.setFrozenRemarks(frozenRemarks);
            unfreezeLog.setUserId(freeze.getUserId());
            unfreezeLog.setUnfreezeDate(DateUtil.date(new Date()));
            this.unfreezeLogMapper.insert(unfreezeLog);

            // 模拟异常
            // int i = 1 / 0;

            // 删除对应的记录
            userFreezeMapper.deleteById(freeze.getId());

            // 删除redis中的记录
            if (redisTemplate.hasKey(CacheKey.FREEZE_PREFIX + userId)) {
                redisTemplate.delete(CacheKey.FREEZE_PREFIX + userId);
            }

            return ResponseEntity.ok(MESSAGE);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResult.error());
        }
    }

    /**
     * Mr.Seven的基操
     */
    public void autoUnfreeze() {
        List<UserFreeze> freezeList = userFreezeMapper.selectList(null);

        for (UserFreeze freeze : freezeList) {
            // 得到封禁的天数
            int day = calculateDay(freeze);

            // 只要不是永久封禁就执行
            if (day != -1) {
                // 拿到封禁的时间
                Date freezeDate = freeze.getFreezeDate();
                // 获取当前时间
                Date now = new Date();
                if (DateUtil.offsetDay(freezeDate, day).toDateStr().equals(DateUtil.date(now).toDateStr())) {
                    this.unfreezeUser(freeze.getUserId(), "到期自动解封", "使用定时器");
                }
            }
        }
    }

    /**
    Mr.Seven的基操
     */
    private int calculateDay(UserFreeze freeze) {
        int day = 0;
        // 如果为1,是3天
        if (freeze.getFreezingTime() == 1) {
            day = 3;
        } else if (freeze.getFreezingTime() == 2) {
            day = 7;
        } else if (freeze.getFreezingTime() == 3) {
            // 如果是永久封禁,记录为-1
            day = -1;
        }
        return day;
    }

    /**
     * Mr.Seven的基操
     * @param userId
     * @return
     */
    public UserFreeze findUserFreezeByUserId(Long userId) {
        QueryWrapper<UserFreeze> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.userFreezeMapper.selectOne(wrapper);
    }

    public ResponseEntity queryFreezeByUserId(Long userId) {
        QueryWrapper<UserFreeze> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserFreeze freeze = userFreezeMapper.selectOne(wrapper);
        return ResponseEntity.ok(freeze);
    }

}
